<template>
  <div class="TchmanageBox">
    <div class="topTitle">教师管理</div>
    <div style="margin:20px 0;">
      <div class="label_hint">添加教师</div>
      <div class="label_content">
        <el-input v-model="keyWord" placeholder="请输入内容" style="width:300px;" @focus="dialog = true"></el-input>
        <el-button type="primary" @click="saveTeacher">保 存</el-button>
      </div>
    </div>
    <div class="teacher_list_box">
      <div class="label_hint">已添加教师</div>
      <div class="label_content">
        <div v-for="(item, index) in teacherList" :key="index" class="teacher_list">
          <i class="el-icon-rank" style="font-size: 20px;"></i>
          <i class="el-icon-user-solid" style="font-size: 40px; padding:0 10px;"></i>
          <span style="font-size: 20px;margin-left: 30px;">{{ item.name }}</span>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            style="margin-left:auto;"
            @click="removeList(index)"
          >删除
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog title="选择教师" :visible.sync="dialog" width="500px">
      <el-row>
        <el-input
          v-model="teacherName"
          clearable
          placeholder="请输入教师名称或关键字"
          style="width:200px;"
          @clear="filterTable = tableData"
          @keyup.enter.native="searchTeacher"
        ></el-input>
        <el-button type="primary" @click="searchTeacher">搜 索</el-button>
      </el-row>
      <el-table
        type="selection"
        ref="multipleTable"
        :data="newTable"
        tooltip-effect="dark"
        :row-key="getRowKey"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip></el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="currentPage"
        :page-size="currentSize"
        :total="filterTable.length"
        style="margin-top:20px"
      ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import eventBus from '@/eventBus'
  import {getTenantId} from '@/utils/auth'
  import {addTeacherToCourse, updateCourse} from '@/api/subject/course'
  import {getEduxcloudTeacherPager} from '@/api/user/user' // 数据接口

  export default {
    data() {
      return {
        // 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
        getRowKey(row) {
          return row.id
        },
        keyWord: '',
        teacherIds: '',
        teacherNames: '',
        dialog: false,
        currentPage: 1,
        currentSize: 5,
        teacherList: [],
        EduxcloudCourse: {},
        teacherName: '',
        filterTable: [],
        tableData: [],
        multipleSelection: [],
        listQuery: {
          nickName: '',
          tenantId: getTenantId(),
          page: 1,
          limit: 20
        },
      }
    },
    mounted() {
      // 请求后的数据赋值给tableData， filterTable为搜索筛查表，newTable是分页多选后的表
      this.filterTable = this.tableData;
      this.acceptWord();
      this.getTeacherListData();
    },
    computed: {
      newTable() {
        return this.filterTable.slice(
          (this.currentPage - 1) * this.currentSize,
          this.currentPage * this.currentSize
        )
      }
    },
    methods: {
      removeList(index) {
        this.teacherList.splice(index, 1)
      },
      // 接口获取数据
      getTeacherListData() {
        getEduxcloudTeacherPager(this.listQuery).then(response => {
          this.tableData = response.data.items;
          this.filterTable = response.data.items;
          this.total = response.data.total;
          this.tableData.map(item => {
            if (this.$route.params.teacherIds) {
              if (this.$route.params.teacherIds.match(item.id)) {
                //包含；
                this.teacherList.push({
                  id: item.id,
                  name: item.name
                })
              }
            }
          });
        })
      },
      updateCourse() {
        updateCourse(this.EduxcloudCourse).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      // 接收兄弟传值
      acceptWord() {
        eventBus.$on('acceptEduxcloudCourseId', data => {
          console.log('teachermanage accept acceptEduxcloudCourseId:' + data);
          this.EduxcloudCourse.id = data
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleCancel() {
        // this.$emit('cancelClick')
        this.clearDialog()
      },
      handleConfirm() {
        if (this.multipleSelection.length < 1) {
          this.$message.warning('请选择教师');
          return
        }
        // this.$emit('confirmClick', this.multipleSelection)
        this.teacherList.push(...this.multipleSelection);
        this.clearDialog()
      },
      saveTeacher() {
        if (this.teacherList.length > 0 && Array.isArray(this.teacherList)) {
          for (let i = 0; i < this.teacherList.length; i++) {
            this.teacherIds += ',' + this.teacherList[i].id;
            this.teacherNames += ',' + this.teacherList[i].name
          }
          console.log("teacherIds:" + this.teacherIds);
          console.log("teacherNames:" + this.teacherNames);
          if (this.EduxcloudCourse.id) {
          } else {
            this.EduxcloudCourse.id = this.$route.params.id;
          }
          addTeacherToCourse(this.EduxcloudCourse.id, this.teacherIds, this.teacherNames).then(() => {
            this.$notify({title: '成功', message: '成功', type: 'success', duration: 2000});
          })
        } else {
          this.$message.error('请选择老师!')
        }
      },
      clearDialog() {
        this.dialog = false;
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = []
      },
      searchTeacher() {
        // 如果有选择教师先清空多选数据
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
        var search = this.teacherName;
        if (search) {
          this.filterTable = this.tableData.filter(function (dataNews) {
            return Object.keys(dataNews).some(function (key) {
              return ~String(dataNews[key])
                .toLowerCase()
                .indexOf(search)
            })
          })
        } else {
          this.filterTable = this.tableData
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .TchmanageBox {
    padding: 10px;

    .topTitle {
      font-size: 16px;
      padding-bottom: 20px;
      border-bottom: 1px solid #eee;
    }

    .label_hint {
      display: inline-block;
      font-size: 16px;
      margin-left: 100px;
      width: 100px;
      text-align: right;
    }

    .label_content {
      display: inline-block;
      margin-left: 20px;
    }

    .teacher_list_box {
      margin: 20px 0;
      display: flex;
      align-items: baseline;
    }

    .teacher_list {
      width: 380px;
      border: 1px solid #ddd;
      margin-bottom: 10px;
      padding: 2px 10px;
      display: flex;
      align-items: center;
    }
  }
</style>
